package com.water.app.Controller.shopping;

import com.water.app.AddressParam;
import com.water.app.Constant;
import com.water.app.Result;
import com.water.app.address;
import com.water.app.interfaces.shopping.addressService;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/api")
public class AddressController {
    private static final Logger log= LoggerFactory.getLogger(AddressController.class);

    @Autowired
    private addressService addressService;
    @Autowired
    private com.water.app.mapper.shoppingMapper shoppingMapper;

    @PostMapping("/addAddress")
    public Result addAddress(@RequestBody AddressParam address){
        String addres=address.getAddress();
        String email=address.getEmail();
        String name=address.getName();
        log.info("address:{}",addres);
        int userId=Constant.THREAD_LOCAL.get();
        if (addres==null||addres.isEmpty()){
            log.info("地址不能为空");
            return Result.error("地址不能为空");
        }
        if(email==null||email.isEmpty()){
            log.info("邮箱不能为空");
            return Result.error("邮箱不能为空");
        }
        if(name==null||name.isEmpty()){
            log.info("收货人不能为空");
            return Result.error("收货人不能为空");
        }
        Integer number= addressService.selectAddressNumberByUserId(userId);
        if(number>=3){
            return Result.error("最多只能添加三条地址");
        }
        boolean result= addressService.insertAddress(addres,userId,email,name);
        if(!result){
            log.info("新增地址失败");
            return Result.error("新增地址失败");
        }
        log.info("新增地址成功");
        return Result.success("新增地址成功");
    }

    @PostMapping("/selectAddress")
    public Result selectAddress(){
        log.info("正在查询地址");
        Integer userId = Constant.THREAD_LOCAL.get();
        List<address> list= addressService.selectAddressByUserId(userId);
        return Result.success(1,"查询地址成功",list);
    }

    @PutMapping("/reviseAddress")
    public Result reviseAddress(@RequestBody address address){
        log.info("正在修改地址:{}",address);
        Integer userId=Constant.THREAD_LOCAL.get();
        boolean result=addressService.reviseAddress(address,userId);
        if(!result){
            log.info("修改地址失败");
            return Result.error("修改地址失败");
        }
        log.info("修改地址成功");
        return Result.success("修改地址成功");
    }

    @PostMapping("/deleteAddress/{id}")
    public Result deleteAddress(@PathVariable int id){
        log.info("id:{}",id);
        boolean result= addressService.deleteById(id);
        if(result){
            log.info("删除地址成功");
            return Result.success("删除地址成功");
        }else {
            log.info("删除地址失败");
            return Result.error("删除地址失败");
        }
    }

}
